<?php

namespace backend\controllers;

use backend\models\PackageInitiationPlan;
use common\models\Country;
use common\models\Package;
use common\models\Project;
use common\models\ProjectTeam;
use common\models\ProjectInvestigationFile;
use common\models\ProjectInvestigationLawsuit;
use common\models\ProjectInvestigationStakeholder;
use common\models\ProjectLike;
use common\models\ProjectUpdateLog;
use common\models\Responses;
use common\models\UploadImgForm;
use common\models\UserModel;
use Yii;
use common\models\ProjectInvestigation;
use common\models\ProjectInvestigationSearch;
use yii\data\Pagination;
use yii\db\Exception;
use yii\db\Query;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\widgets\LinkPager;

/**
 * 尽调报告——债权基本情况控制器
 * @auth zhao shou qiang
 */
class ProjectInvestigationController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return parent::behaviors();

//        return [
//            'verbs' => [
//                'class' => VerbFilter::className(),
//                'actions' => [
//                    'delete' => ['POST'],
//                ],
//            ],
//        ];
    }

    /**
     * 尽调评估--编辑页
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProjectInvestigationSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $projectId = (int)Yii::$app->request->get('project_id');
        $packageId = (int)Yii::$app->request->get('package_id');
        if ($projectId <= 0 || $packageId <= 0) {
            Yii::$app->user->setReturnUrl(Yii::$app->request->referrer);
        }

        /**--------------------------  头部信息start --------------------------------**/
        $data['Id'] = intval(\Yii::$app->request->get('project_id'));
        $data['package_id'] = intval(\Yii::$app->request->get('package_id'));
        $data['mortgage_id'] = intval(\Yii::$app->request->get('mortgage_id', 1));
        $data = Project::getProjectInfoData($data);
        //$data['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');

        $data['user'] = (new \yii\db\Query())->select('*')->from('user')->all();
        $data['data']['res']['userChief'] = (new \yii\db\Query())->select('*')->from('user')->andWhere(['=', 'is_leader', 1])->all();

//            $projectInfoData['history'] = (new \yii\db\Query())->from(PackageTransfer::tableName())->where(['=', 'project_id', $projectId])->all();
        //$projectInfoData['note'] = (new \yii\db\Query())->from(ProjectPreEvaluationOtherNote::tableName())->where(['=', 'project_id', $projectId])->one();

        //所有部门人员
        $userModel = new UserModel();
        $where = ['not in', 'department',
            ['总裁办', '风控管理中心', '财务部', '技术部', '品牌部', '新大唐学院', '人力行政部',
                'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration','',
            ]];
        $data['data']['res']['Base']['departments'] = $userModel->getDepartmentUsers($where);
        $data['data']['res']['Base']['access_users_ids'] = $data['data']['res']['Base']['access_users'] != "" ? explode(",", $data['data']['res']['Base']['access_users']) : "";
        $data['data']['res']['Base']['access_users'] = $this->getAccessUsers($data['data']['res']['Base']['access'], $data['data']['res']['Base']['access']);
        //是否关注
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['flow'] = 1;
        } else {
            $data['data']['res']['Base']['flow'] = 0;
        }
        //是否亮点
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 2, 'user_id' => Yii::$app->user->id])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['light_spot'] = 1;
        } else {
            $data['data']['res']['Base']['light_spot'] = 0;
        }
        //获取配置团队成员信息
        $teamZJ = array_column($data['data']['res']['teamZJ'], 'id');
        $teamFZR = array_column($data['data']['res']['teamFZR'], 'id');
        $teamXZR = array_column($data['data']['res']['teamXZR'], 'id');

//        $teamS = array_merge($teamZJ, $teamFZR, $teamXZR);
//        $data['data']['res']['teamInfo'] = Project::getTeamUserData($teamS);

        $data['data']['res']['teamInfo']['teamZJ'] = array();
        $data['data']['res']['teamInfo']['teamFZR'] = array();
        $data['data']['res']['teamInfo']['teamXZR'] = array();
        $getDepartmentUsersList = (new UserModel())->getDepartmentUsersList();

        if (!empty($teamZJ)) {
            foreach ($teamZJ as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamZJ_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamZJ_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamZJ_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamZJ_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamZJ_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamZJ_array['role'] = '项目总监';
                    $data['data']['res']['teamInfo']['teamZJ'][] = $teamZJ_array;
                }
            }
        }

        if (!empty($teamFZR)) {
            foreach ($teamFZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamFZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamFZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamFZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamFZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamFZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamFZR_array['role'] = '项目经理';
                    $data['data']['res']['teamInfo']['teamFZR'][] = $teamFZR_array;
                }
            }
        }

        if (!empty($teamXZR)) {
            foreach ($teamXZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamXZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamXZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamXZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamXZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamXZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamXZR_array['role'] = '团队成员';
                    $data['data']['res']['teamInfo']['teamXZR'][] = $teamXZR_array;
                }
            }
        }

        //项目所属资产包
        $packageInfo = Package::findOne($packageId);
        if (!empty($packageInfo)) {
            $data['data']['res']['packageName'] = $packageInfo->title;
            $data['data']['res']['Base']['code'] = $packageInfo->code;
            $province = '';
            $city = '';
            $country = new Country();
            if ($packageInfo->province > 0) {
                $province = $country->getName($packageInfo->province);
            }
            if ($packageInfo->city > 0) {
                $city = $country->getName($packageInfo->city);
            }
            $data['data']['res']['Base']['country'] = $province . $city;
        } else {
            $data['data']['res']['packageName'] = '';
            $data['data']['res']['Base']['code'] = '';
            $data['data']['res']['Base']['country'] = '';
        }
        //$data['data']['res']['packageName'] = (new \yii\db\Query())->from(Package::tableName())->where(['=', 'id', $packageId])->one()['title'];
        /**--------------------------  头部信息end --------------------------------**/

        //项目详情
        $project = Project::findOne($projectId);

        //债权基本情况及总结
        $investigation = ProjectInvestigation::find()->where(['project_id' => $projectId])->one();
        if (empty($investigation)) {
            $investigation = new ProjectInvestigation();
            $investigation->project_id = $project->id;
            $investigation->borrower = $project->borrower;
            $investigation->principal = $project->principal;
            $investigation->interest = $project->interest;
            $investigation->created_at = date('Y-m-d H:i:s', time());
            $investigation->save();
        }
        $investigation->principal = $this->set_number_format2($investigation->principal);
        $investigation->interest = $this->set_number_format2($investigation->interest);

        $investigationLawsuit = new ProjectInvestigationLawsuit();
        $stakeholder = new ProjectInvestigationStakeholder();
        //1借款人及资产情况 一条
        $borrower = $stakeholder->getOne(['project_id' => $projectId, 'stakeholder_type' => ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_BORROWER]);
        if (empty($borrower)) {
            $stakeholder2 = clone $stakeholder;
            $stakeholder2->project_id = $project->id;
            $stakeholder2->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_BORROWER;
            $stakeholder2->stakeholder_title = $project->borrower;
            $stakeholder2->borrower = $project->management_status;
            $stakeholder2->created_at = date('Y-m-d H:i:s', time());
            $stakeholder2->save();
            $borrower = $stakeholder2;
        }
        $where = [
            'project_id' => $projectId,
            'stakeholder_id' => $borrower->id,
        ];
        $borrower_lawsuit_list = $investigationLawsuit->getList($where);

        //2抵押人及资产情况 多条
        $mortgagorList = $stakeholder->getAll(['project_id' => $projectId, 'stakeholder_type' => ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_MORTGAGOR]);
        if (empty($mortgagorList)) {
            $stakeholderMortgagorModal =  clone $stakeholder;
            $stakeholderMortgagorModal->project_id = $project->id;
            $stakeholderMortgagorModal->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_MORTGAGOR;
            $stakeholderMortgagorModal->stakeholder_title = '';
            $stakeholderMortgagorModal->created_at = date('Y-m-d H:i:s', time());
            $stakeholderMortgagorModal->save();

            $stakeholderMortgagorOne = $stakeholderMortgagorModal;
            //$stakeholderMortgagorOne = $stakeholder;
            $mortgagor_lawsuit_list = array();
        } else {
            $stakeholderMortgagorOne = $mortgagorList[0];
            $where = [
                'project_id' => $projectId,
                'stakeholder_id' => $stakeholderMortgagorOne->id,
            ];
            $mortgagor_lawsuit_list = $investigationLawsuit->getList($where);
        }

        //3保证人及资产情况 多条
        $guarantorList = $stakeholder->getAll(['project_id' => $projectId, 'stakeholder_type' => ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_GUARANTOR]);
        if (empty($guarantorList)) {
            $stakeholderGuarantorModal =  clone $stakeholder;
            $stakeholderGuarantorModal->project_id = $project->id;
            $stakeholderGuarantorModal->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_GUARANTOR;
            $stakeholderGuarantorModal->stakeholder_title = '';
            $stakeholderGuarantorModal->created_at = date('Y-m-d H:i:s', time());
            $stakeholderGuarantorModal->save();

            $stakeholderGuarantorOne = $stakeholderGuarantorModal;
            //$stakeholderGuarantorOne = $stakeholder;
            $guarantor_lawsuit_list = array();
        } else {
            $stakeholderGuarantorOne = $guarantorList[0];
            $where = [
                'project_id' => $projectId,
                'stakeholder_id' => $stakeholderGuarantorOne->id,
            ];
            $guarantor_lawsuit_list = $investigationLawsuit->getList($where);
        }

        //4其他承债人及资产情况 多条
        $otherList = $stakeholder->getAll(['project_id' => $projectId, 'stakeholder_type' => ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_OTHER]);
        if (empty($otherList)) {
            $stakeholderOtherModal =  clone $stakeholder;
            $stakeholderOtherModal->project_id = $project->id;
            $stakeholderOtherModal->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_OTHER;
            $stakeholderOtherModal->stakeholder_title = '';
            $stakeholderOtherModal->created_at = date('Y-m-d H:i:s', time());
            $stakeholderOtherModal->save();

            $stakeholderOtherOne = $stakeholderOtherModal;
            //$stakeholderOtherOne = $stakeholder;
            $other_lawsuit_list = array();
        } else {
            $stakeholderOtherOne = $otherList[0];
            $where = [
                'project_id' => $projectId,
                'stakeholder_id' => $stakeholderOtherOne->id,
            ];
            $other_lawsuit_list = $investigationLawsuit->getList($where);
        }

        //关键附件  第一页，每页默认10条
        $page = 1;
        $offset = 10;//默认每页显示条数
        $projectInvestigationFile = new ProjectInvestigationFile();
        $count = $projectInvestigationFile->getCounts(['project_id' => $projectId]); //总条数
        $fileList = $projectInvestigationFile->getList(['project_id' => $projectId], $offset, ($page - 1) * $offset); //第一页列表
        //分页
        //'totalCount' 为数据总数
        //'pageSize' 为每页显示数
        //'pageSizeParam'=>false, 可将分页路径中per-page参数隐藏去掉
        //'pageParam' => 'p', 可更改分页url中分页参数name名称
        //'route' => false, 当分页在于首页时隐藏掉路由，将/site/index?p=1变为/?p=1
        //'validatePage' => false, 取消分页验证,当手动输入page=20时不再跳到page=1
        $query = ProjectInvestigationFile::find()->where(['project_id' => $projectId]);
        $countQuery = clone $query;
        $pages = new Pagination(['pageSize' => $offset, 'totalCount' => $countQuery->count()]);
        $linkpager = LinkPager::widget([
            'pagination' => $pages,
            'hideOnSinglePage' => false,
            'maxButtonCount' => 10, //默认显示10页
            'nextPageLabel' => '下一页',
            'prevPageLabel' => '上一页',
            'firstPageLabel' => '首页',
            'lastPageLabel' => '尾页',
            //'options' => ['class' => 'm-pagination'],
        ]);

        $fileLinkPager = array(
            'list' => $fileList,
            'count' => $count,
            'linkPager' => $linkpager,
            'page' => $page
        );

        $data['data']['res']['team'] = (new \yii\db\Query())->from(ProjectTeam::tableName())->select('*')->where(['=', 'project_id', $projectId])->one();
        if (!empty($projectInfoData['team'])) {
            //通过id获取总监名称
            $leaderIdArr = [];
            if (!empty($projectInfoData['team']['manager']) && preg_match('/,/', $projectInfoData['team']['manager'])) {
                $leaderIdArr = array_unique(explode(',', $projectInfoData['team']['manager']));
            } else if (is_string($projectInfoData['team']['manager'])) {
                $leaderIdArr = $projectInfoData['team']['manager'];
            }
            $leader_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $leaderIdArr])->all();
            $data['data']['res']['teamZJ'] = PackageInitiationPlan::pieceUsername($leader_name);
            //通过id获取负责人名称
            $ownerIdArr = [];
            if (!empty($projectInfoData['team']['owner']) && preg_match('/,/', $projectInfoData['team']['owner'])) {
                $ownerIdArr = array_unique(explode(',', $projectInfoData['team']['owner']));
            } else if (is_string($projectInfoData['team']['owner'])) {
                $ownerIdArr = $projectInfoData['team']['owner'];
            }
            $owner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $ownerIdArr])->all();
            $data['data']['res']['teamFZR'] = PackageInitiationPlan::pieceUsername($owner_name);
            //通过id获取协助人
            $partnerIdArr = [];
            if (!empty($projectInfoData['team']['partner']) && preg_match('/,/', $projectInfoData['team']['partner'])) {
                $partnerIdArr = array_unique(explode(',', $projectInfoData['team']['partner']));
            } else if (is_string($projectInfoData['team']['partner'])) {
                $partnerIdArr = $projectInfoData['team']['partner'];
            }
            $partner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $partnerIdArr])->all();
            $data['data']['res']['teamXZR'] = PackageInitiationPlan::pieceUsername($partner_name);
        } else {
            $data['data']['res']['teamZJ'] = [];
            $data['data']['res']['teamFZR'] = [];
            $data['data']['res']['teamXZR'] = [];
        }

        //$this->layout = 'main2';
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'projectId' => $projectId,
            'packageId' => $packageId,
            'projectModel' => $project,

            'data' => $data['data']['res'],

            //债权基本情况
            'investigation' => $investigation,
            //借款人
            'borrower' => $borrower,
            'borrower_lawsuit_list' => $borrower_lawsuit_list,
            //抵押人
            'stakeholderMortgagorOne' => $stakeholderMortgagorOne,
            'mortgagorList' => $mortgagorList,
            'mortgagor_lawsuit_list' => $mortgagor_lawsuit_list,
            //保证人
            'stakeholderGuarantorOne' => $stakeholderGuarantorOne,
            'guarantorList' => $guarantorList,
            'guarantor_lawsuit_list' => $guarantor_lawsuit_list,
            //其它承债人
            'stakeholderOtherOne' => $stakeholderOtherOne,
            'otherList' => $otherList,
            'other_lawsuit_list' => $other_lawsuit_list,

            'fileLinkPager' => $fileLinkPager,
            'uploadImgForm' => new UploadImgForm()
        ]);
    }

    /**
     * 保存——干系人及资产情况
     * @return array
     */
    public function actionSaveStakeholder()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $post = Yii::$app->request->post();
            $id = isset($post['id']) ? (int)$post['id'] : 0;
            unset($post['id']);
            $investigationLawsuit = new ProjectInvestigationLawsuit();

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            if ($id === 0) {
                $update_state = false;//false新增，true修改
                $model = new ProjectInvestigationStakeholder();
                $model->created_at = date('Y-m-d H:i:s', time());
            } else {
                $update_state = true;//false新增，true修改
                $model = ProjectInvestigationStakeholder::findOne($id);
                $model->updated_at = date('Y-m-d H:i:s', time());

                //如果是修改判断值是否发生了改变
                $state = false;
                $changedAttributes = array();
                if ($model->id) {
                    foreach ($post['ProjectInvestigationStakeholder'] as $key => $value) {
                        if ($model->$key != $value) {
                            $changedAttributes[$key] = $value;
                            $state = true;
                        }
                    }
                }

                //解锁
                if ($model->stakeholder_type == 1) {
                    $res = $this->unlocking($model, $userId);
                } else {
                    $models = ProjectInvestigationStakeholder::find()->where(array('project_id' => $model->project_id, 'stakeholder_type' => $model->stakeholder_type))->all();
                    $res = $this->more_unlocking($models, $userId);
                }
                if (!$res['state']) {
                    return Responses::response400($res['msg'], true);
                }

                if (!$state) {
                    if ($model->id>0) {
                        $where = [
                            'project_id' => $model->project_id,
                            'stakeholder_id' => $model->id,
                        ];
                        $lawsuit_list = $investigationLawsuit->getList($where);
                    } else {
                        $lawsuit_list = array();
                    }
                    return Responses::response200(array('model' => $model, 'lawsuitList' => $lawsuit_list), 1, '保存成功');
                    //return Responses::response200($model, 1, '保存成功');
                    //return Responses::response400('没有做任何修改', true);
                }
            }


            if (isset($model->stakeholder_type)) {
                switch ($model->stakeholder_type) {
                    case 1:
                        $module = ProjectUpdateLog::MODULE_BORROWER;
                        break;
                    case 2:
                        $module = ProjectUpdateLog::MODULE_PLEDGER;
                        break;
                    case 3:
                        $module = ProjectUpdateLog::MODULE_WARRANTOR;
                        break;
                    case 4:
                        $module = ProjectUpdateLog::MODULE_OTHER;
                        break;
                    default:
                }
            }

            // TODO 更新数据更新记录
            if ($update_state) {
                $res = $model->setUpdateLog($id, $model->project_id, $changedAttributes, $userId, $module, 2);
                if (!$res['state']) {
                    throw new \Exception($res['msg']);
                }
            }

            if ($model->load($post) && $model->save()) {
                if (isset($model->stakeholder_type)) {
                    switch ($model->stakeholder_type) {
                        case 1:
                            $module = ProjectUpdateLog::MODULE_BORROWER;
                            break;
                        case 2:
                            $module = ProjectUpdateLog::MODULE_PLEDGER;
                            break;
                        case 3:
                            $module = ProjectUpdateLog::MODULE_WARRANTOR;
                            break;
                        case 4:
                            $module = ProjectUpdateLog::MODULE_OTHER;
                            break;
                        default:
                    }
                }

                // TODO 新增数据更新记录
                if (!$update_state) {
                    $res = $model->setUpdateLog($model->id, $model->project_id, $model, $userId, $module, 1);
                    if (!$res['state']) {
                        throw new \Exception($res['msg']);
                    }
                }

                $info = ProjectInvestigationStakeholder::findOne($model->id);
                $where = [
                    'project_id' => $info->project_id,
                    'stakeholder_id' => $info->id,
                ];
                $lawsuit_list = $investigationLawsuit->getList($where);
                return Responses::response200(array('model' => $info, 'lawsuitList' => $lawsuit_list), 1, '保存成功');
            } else {
                $error = $model->getFirstErrors();
                $message = '';
                if (!empty($error)) {
                    foreach ($error as $value) {
                        $message .= $value;
                    }
                    $tmpStr = strip_tags($message);
                    $tmpLen = mb_strlen($tmpStr);
                    $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                }
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 删除——干系人及资产情况
     * @return array
     */
    public function actionDeleteStakeholder()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $id = Yii::$app->request->post('id');
            $stakeholder_type = Yii::$app->request->post('stakeholder_type');

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $model = ProjectInvestigationStakeholder::find()->where(['id' => $id, 'stakeholder_type' => $stakeholder_type])->one();
                if (!empty($model)) {
                    //TODO 添加更新日志
                    switch ($stakeholder_type) {
                        case 1:
                            $module = ProjectUpdateLog::MODULE_BORROWER;
                            break;
                        case 2:
                            $module = ProjectUpdateLog::MODULE_PLEDGER;
                            break;
                        case 3:
                            $module = ProjectUpdateLog::MODULE_WARRANTOR;
                            break;
                        case 4:
                            $module = ProjectUpdateLog::MODULE_OTHER;
                            break;
                        default:
                    }
                    $res = (new ProjectInvestigationStakeholder())->setUpdateLog($model->id, $model->project_id, array(), $userId, $module, 3);
                    if (!$res['state']) {
                        throw new Exception($res['msg']);
                    }

                    if ($model->delete()) {
                        $transaction->commit();
                        return Responses::response200(array(), 1, '删除成功');
                    } else {
                        throw new \Exception('删除失败');
                    }
                } else {
                    throw new \Exception('系统错误');
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 详情——干系人及资产情况
     * @return array
     */
    public function actionStakeholderInfo()
    {
        if (Yii::$app->request->isAjax) {
            $id = Yii::$app->request->post('id');
            $stakeholder_type = Yii::$app->request->post('stakeholder_type');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($id > 0) {
                $model = ProjectInvestigationStakeholder::find()->where(['id' => $id, 'stakeholder_type' => $stakeholder_type])->one();
                if (!empty($model)) {
                    $where = [
                        'project_id' => $model->project_id,
                        'stakeholder_id' => $model->id,
                    ];
                    $lawsuitModel = new ProjectInvestigationLawsuit();
                    $lawsuitList = $lawsuitModel->getList($where);
                } else {
                    $lawsuitList = array();
                }
            } else {
                $model = new ProjectInvestigationStakeholder();
                $lawsuitList = array();
            }
            $data = [
                'model' => $model,
                'lawsuitList' => $lawsuitList
            ];
            return Responses::response200($data, 1, '删除成功');
        }
    }

    /**
     * 保存——债权基本情况
     * @return array
     */
    public function actionSaveInvestigation()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $post = Yii::$app->request->post();
            $step_type = Yii::$app->request->get('step_type');
            $id = isset($post['id']) ? (int)$post['id'] : 0;

            unset($post['id']);
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $changedAttributes = array(); //修改属性值
//            if ($id === 0) {
//                $model = new ProjectInvestigation();
//                $model->created_at = date('Y-m-d H:i:s', time());
//            } else {
            $model = ProjectInvestigation::findOne($id);
            $model->updated_at = date('Y-m-d H:i:s', time());

            //判断是否加锁
            $isLockedData = $this->is_locked($model, $userId);
            if (!$isLockedData['state']) {
                return Responses::response400($isLockedData['message'], true);
            }

            //判断修改值是否发生了改变
            if (isset($post['ProjectInvestigation']['principal'])) {
                $principal = isset($post['ProjectInvestigation']['principal']) ? $post['ProjectInvestigation']['principal'] : '0';
                $post['ProjectInvestigation']['principal'] = $this->set_number_format($principal);
            }

            if (isset($post['ProjectInvestigation']['interest'])) {
                $interest = isset($post['ProjectInvestigation']['interest']) ? $post['ProjectInvestigation']['interest'] : '0';
                $post['ProjectInvestigation']['interest'] = $this->set_number_format($interest);
            }
            $state = false;
            if ($model->id) {
                foreach ($post['ProjectInvestigation'] as $key => $value) {
                    if ($model->$key != $value) {
                        $changedAttributes[$key] = $value;
                        $state = true;
                    }
                }
            }

            if (!$state) {
                //return Responses::response400('没有做任何修改', true);
                //解锁
                if ($model->lock_timestamp !== null || $model->lock_user !== null) {
                    $model->lock_timestamp = null;
                    $model->lock_user = null;
                    if (!$model->save()) {
                        return Responses::response400('保存失败', true);
                    }
                }
                $model->principal = $this->set_number_format2($model->principal);
                $model->interest = $this->set_number_format2($model->interest);
                return Responses::response200($model, 1, '保存成功');
            }
//            }

            //TODO 添加修改日志
            if ($step_type == 2) {
                $model_type = ProjectUpdateLog::MODULE_SUMMARIZE;
            } else {
                $model_type = ProjectUpdateLog::MODULE_INVESTIGATION;
            }
            $res = $model->setUpdateLog($id, $model->project_id, $changedAttributes, $userId, $model_type, 2);
            if (!$res['state']) {
                throw new \Exception($res['msg']);
            }

            $post['ProjectInvestigation']['lock_user'] = null;
            $post['ProjectInvestigation']['lock_timestamp'] = null;
            if ($model->load($post) && $model->save()) {
                if ($model->id) {
                    $id = $model->id;
                }
                $info = ProjectInvestigation::findOne($id);
                $info->principal = $this->set_number_format2($info->principal);
                $info->interest = $this->set_number_format2($info->interest);
                return Responses::response200($info, 1, '保存成功');
            } else {
                $error = $model->getFirstErrors();
                $message = '';
                if (!empty($error)) {
                    foreach ($error as $value) {
                        $message .= $value;
                    }
                    $tmpStr = strip_tags($message);
                    $tmpLen = mb_strlen($tmpStr);
                    $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                }
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 取消——债权基本情况并返回原来值
     * @return array
     */
    public function actionCancelInvestigation()
    {
        if (Yii::$app->request->isAjax) {
            $id = (int)Yii::$app->request->post('id');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $model = ProjectInvestigation::findOne($id);
            if ($model === null) {
                return Responses::response400('数据不存在', true);
            } else {
                //解锁
                if ($model->lock_user !== null || $model->lock_timestamp !== null) {
                    $model->lock_timestamp = null;
                    $model->lock_user = null;
                    if (!$model->save()) {
                        return Responses::response400('取消失败', true);
                    }
                }
                return Responses::response200($model, 1, '取消成功');
            }
        }
    }

    /**
     * 验证——债权基本情况
     * @return array
     */
    public function actionValidateInvestiogatin($id = null)
    {
        $model = $id === null ? new ProjectInvestigation() : ProjectInvestigation::findOne($id);
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model->load(Yii::$app->request->post());
        return \yii\widgets\ActiveForm::validate($model);
    }

    /**
     * 保存——干系人及资产涉诉情况
     *  接受每条数据  $post['info'][0][...] ，$post['info'][1][...] ...
     * @return array
     */
    public function actionSaveLawsuit()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $post = Yii::$app->request->post();
            $project_id = (int)$post['project_id'];
            $stakeholder_id = (int)$post['stakeholder_id'];
            unset($post['project_id']);
            unset($post['stakeholder_id']);

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            if (!$stakeholder_id) {
                return Responses::response400('请添加干系人员', true);
            }

            $transaction = Yii::$app->db->beginTransaction();
            try {
                if (isset($post['info']) && !empty($post['info']) && is_array($post['info'])) {
                    $add_line = ''; //新增的行数
                    $edit_line = ''; //修改的行数
                    $line = ''; //未改变的行数
                    $info = [];  //编辑后的每条数据id，根据$post['info'][1] 下标一一对应
                    $status = false; //是否有编辑（值改变或添加新数据则为true）


                    foreach ($post['info'] as $key => $value) {
                        $value['id'] = (int)$value['id'];
                        if ($value['id'] > 0) {
                            $model = ProjectInvestigationLawsuit::findOne($value['id']);
                            //判断修改值是否发生了改变
                            $state = false;
                            $changedAttributes = array();
                            foreach ($value as $k => $v) {
                                if ($model->$k != $v) {
                                    $state = true;
                                    $model->$k = $v;
                                    $changedAttributes[$k] = $v;
                                }
                            }
                            if (!$state) {
                                $line .= ($key + 1) . ',';
                            } else {
                                $res = $model->setUpdateLog($model->id, $model->project_id, $changedAttributes, $userId, ProjectUpdateLog::MODULE_LAWSUIT, 2);
                                if (!$res['state']) {
                                    throw new \Exception($res['msg']);
                                }

                                if (!$model->save()) {
                                    $error = $model->getFirstErrors();
                                    $message = '';
                                    if (!empty($error)) {
                                        foreach ($error as $val) {
                                            $message .= $val;
                                        }
                                        $tmpStr = strip_tags($message);
                                        $tmpLen = mb_strlen($tmpStr);
                                        $message = "第{$key}行" . mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                                        throw new Exception($message);
                                    }
                                }
                                $edit_line .= ($key + 1) . '，';
                                $status = true;
                            }
                            $info[$key] = $value['id'];
                        } else {
                            $model = new ProjectInvestigationLawsuit();
                            $model->project_id = $project_id;
                            $model->stakeholder_id = $stakeholder_id;
                            $model->records_number = $value['records_number'];
                            $model->accuser = $value['accuser'];
                            $model->defendant = $value['defendant'];
                            $model->money = $value['money'];
                            $model->court = $value['court'];
                            $model->lawsuit_content = $value['lawsuit_content'];
                            if (!$model->save()) {
                                $error = $model->getFirstErrors();
                                $message = '';
                                if (!empty($error)) {
                                    foreach ($error as $val) {
                                        $message .= $val;
                                    }
                                    $tmpStr = strip_tags($message);
                                    $tmpLen = mb_strlen($tmpStr);
                                    $message = "第{$key}行" . mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                                    throw new Exception($message);
                                }
                            } else {
                                $res = $model->setUpdateLog($model->id, $model->project_id, $model, $userId, ProjectUpdateLog::MODULE_LAWSUIT, 1);
                                if (!$res['state']) {
                                    throw new \Exception($res['msg']);
                                }
                            }
                            $add_line .= ($key + 1) . ',';
                            $info[$key] = $model->id;
                            $status = true;
                        }
                    }

                    $transaction->commit();

                    if (!$status) {
                        $where = ['project_id' => $project_id, 'stakeholder_id' => $stakeholder_id];
                        $investigationLawsuit = new ProjectInvestigationLawsuit();
                        $list = $investigationLawsuit->getList($where);

                        //解锁
                        $where = array('project_id' => $project_id, 'stakeholder_id' => $stakeholder_id);
                        $models = ProjectInvestigationLawsuit::find()->where($where)->all();
                        if (!empty($models)) {
                            $res = $this->more_unlocking($models, $userId);
                            if (!$res['state']) {
                                throw new \Exception($res['msg']);
                            }
                        }

                        return Responses::response200($list, 1, '保存成功');
                    }

//                    $add_line = trim($add_line, ',');
//                    $edit_line = trim($edit_line, ',');
//                    $line = trim($line, ',');
//                    $msg = '';
//                    if ($line != '') {
//                        $msg .= '第' . $line . '行未改变。';
//                    }
//                    if ($add_line != '') {
//                        $msg .= '第' . $add_line . '行添加成功。';
//                    }
//                    if ($edit_line != '') {
//                        $msg .= '第' . $edit_line . '行修改成功。';
//                    }

                    $where = ['project_id' => $project_id, 'stakeholder_id' => $stakeholder_id];
                    $investigationLawsuit = new ProjectInvestigationLawsuit();
                    $list = $investigationLawsuit->getList($where);

                    //解锁
                    $where = array('project_id' => $project_id, 'stakeholder_id' => $stakeholder_id);
                    $models = ProjectInvestigationLawsuit::find()->where($where)->all();
                    if (!empty($models)) {
                        $res = $this->more_unlocking($models, $userId);
                        if (!$res['state']) {
                            throw new \Exception($res['msg']);
                        }
                    }

                    //return Responses::response200($list, 1, $msg);
                    return Responses::response200($list, 1, '保存成功');
                } else {
                    throw new \Exception('请填写诉讼情况');
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::responseError(array(), $message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::responseError(array(), $message, true);
            }
        }
    }

    /**
     * 删除——干系人及资产涉诉情况
     * @return array
     */
    public function actionDeleteLawsuit()
    {
        if (Yii::$app->request->isAjax) {
            $userId = (int)Yii::$app->user->id;
            $id = (int)Yii::$app->request->post('id');
            $model = ProjectInvestigationLawsuit::find()->where(['id' => $id])->one();
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $transaction = Yii::$app->db->beginTransaction();
            try {
                if ($model !== null) {
                    $res = (new ProjectInvestigationLawsuit())->setUpdateLog($id, $model->project_id, array(), $userId, ProjectUpdateLog::MODULE_LAWSUIT, 3);
                    $re = $model->delete();
                    if ($re && $res['state']) {
                        $transaction->commit();
                        return Responses::response200(array(), 1, '删除成功');
                    }
                }
                throw new \Exception('删除失败');
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 列表——干系人及资产涉诉情况
     * @return array
     */
    public function actionListLawsuit()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $project_id = (int)Yii::$app->request->post('project_id');
            $stakeholder_id = (int)Yii::$app->request->post('stakeholder_id');

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($project_id > 0 && $stakeholder_id > 0) {
                $where = [
                    'project_id' => $project_id,
                    'stakeholder_id' => $stakeholder_id,
                ];
                $investigationLawsuit = new ProjectInvestigationLawsuit();
                $list = $investigationLawsuit->getList($where);
                //解锁
                $models = ProjectInvestigationLawsuit::find()->where($where)->all();
                if (!empty($models)) {
                    $res = $this->more_unlocking($models, $userId);
                    if (!$res['state']) {
                        return Responses::response400($res['msg'], true);
                    }
                }

                return Responses::response200($list, 1, '');
            } else {
                return Responses::response200(array(), 1, '');
            }
        }
    }

    /*获取公开部门显示结果*/
    private function getAccessUsers($access, $accessStr)
    {
        switch ($access) {
            case 2:
                $access_users = (new UserModel())->getUserStr($accessStr);//可访问的用户str
                break;
            case 1:
                $access_users = '私密';
                break;
            default:
                $access_users = '公司全体人员';
                break;
        }
        return $access_users;
    }

    /**
     * 添加——承债人
     * @return array
     */
    public function actionAddStakeholder()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $project_id = (int)Yii::$app->request->post('project_id');
            $stakeholder_type = (int)Yii::$app->request->post('stakeholder_type');

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $model = new ProjectInvestigationStakeholder();
            $model->project_id = $project_id;
            switch ($stakeholder_type) {
                case 1:
                    $model->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_BORROWER;
                    $module = ProjectUpdateLog::MODULE_BORROWER;
                    break;
                case 2:
                    $model->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_MORTGAGOR;
                    $module = ProjectUpdateLog::MODULE_PLEDGER;
                    break;
                case 3:
                    $model->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_GUARANTOR;
                    $module = ProjectUpdateLog::MODULE_WARRANTOR;
                    break;
                case 4:
                    $model->stakeholder_type = ProjectInvestigationStakeholder::STAKEHOLDER_TYPE_OTHER;
                    $module = ProjectUpdateLog::MODULE_OTHER;
                    break;
                default:
            }
            $model->stakeholder_title = '';

            $transaction = Yii::$app->db->beginTransaction();
            try {
                if ($model->save()) {
                    $transaction->commit();
                    //TODO 更新记录
                    $res = $model->setUpdateLog($model->id, $project_id, $model, $userId, $module, 1);
                    if (!$res['state']) {
                        throw new \Exception($res['msg']);
                    }
                    return Responses::response200($model, 1, '');
                } else {
                    $error = $model->getFirstErrors();
                    $message = '';
                    if (!empty($error)) {
                        foreach ($error as $val) {
                            $message .= $val;
                        }
                        $tmpStr = strip_tags($message);
                        $tmpLen = mb_strlen($tmpStr);
                        $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                    }
                    throw new \Exception($message);
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 加解锁——债权基本情况
     *  type 1加锁，2解锁
     * @return array
     */
    public function actionLock()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $project_id = (int)Yii::$app->request->post('project_id');
            $id = (int)Yii::$app->request->post('id');
            $type = (int)Yii::$app->request->post('type');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $model = ProjectInvestigation::find()->where(['id' => $id, 'project_id' => $project_id])->one();
            if ($model !== null) {
                switch ($type) {
                    case 1:
                        //判断别人是否加锁
                        $isLockedData = $this->is_locked($model, $userId);
                        if (!$isLockedData['state']) {
                            return Responses::response400($isLockedData['msg'], true);
                        }

                        $model->lock_user = $userId;
                        $model->lock_timestamp = date('Y-m-d H:i:s', time());
                        if (!$model->save()) {
                            return Responses::response400('加锁失败', true);
                        }
                        break;
                    case 2:
                        $model->lock_user = null;
                        $model->lock_timestamp = null;
                        if (!$model->save()) {
                            return Responses::response400('解锁失败', true);
                        }
                        break;
                    default:
                }
                return Responses::response200(array(), 1, '成功');
            }
            return Responses::response400('该数据不存在', true);
        }
    }

    /**
     * 加解锁——承债人及资产情况
     *  type 1加锁，2解锁
     * @return array
     */
    public function actionStakeholderLock()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $project_id = (int)Yii::$app->request->post('project_id');
            $id = (int)Yii::$app->request->post('id');
            $type = (int)Yii::$app->request->post('type');
            $stakeholder_type = (int)Yii::$app->request->post('stakeholder_type');

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            switch ($type) {
                //加锁
                case 1:
                    if ($stakeholder_type == 1) {
                        $model = ProjectInvestigationStakeholder::find()->where(array('project_id' => $project_id, 'stakeholder_type' => $stakeholder_type, 'id' => $id))->one();
                        if ($model !== null) {
                            //判断别人是否锁定
                            $isLockedData = $this->is_locked($model, $userId);
                            if (!$isLockedData['state']) {
                                return Responses::response400($isLockedData['msg'], true);
                            }

                            $model->lock_user = $userId;
                            $model->lock_timestamp = date('Y-m-d H:i:s', time());
                            if (!$model->save()) {
                                return Responses::response400('加锁失败', true);
                            }
                            return Responses::response200(array(), 1, '加锁成功');
                        }
                    } else {
                        $models = ProjectInvestigationStakeholder::find()->where(array('project_id' => $project_id, 'stakeholder_type' => $stakeholder_type))->all();
                        if (!empty($models)) {
                            $isLockedData = $this->more_is_locked($models, $userId);
                            if (!$isLockedData['state']) {
                                return Responses::response400($isLockedData['msg'], true);
                            }

                            $LockingData = $this->more_locking($models, $userId);
                            if (!$LockingData['state']) {
                                return Responses::response400('加锁失败', true);
                            }
                            return Responses::response200(array(), 1, '加锁成功');
                        }
                    }
                    break;

                //解锁
                case 2:
                    if ($stakeholder_type == 1) {
                        $model = ProjectInvestigationStakeholder::find()->where(array('project_id' => $project_id, 'stakeholder_type' => $stakeholder_type, 'id' => $id))->one();
                        if ($model !== null) {
                            $LockingData = $this->unlocking($model, $userId);
                            if (!$LockingData['state']) {
                                return Responses::response400('解锁失败', true);
                            }
                            return Responses::response200(array(), 1, '解锁成功');
                        }
                    } else {
                        $models = ProjectInvestigationStakeholder::find()->where(array('project_id' => $project_id, 'stakeholder_type' => $stakeholder_type))->all();
                        if (!empty($models)) {
                            $unLockingData = $this->more_unlocking($models, $userId);
                            if (!$unLockingData['state']) {
                                return Responses::response400('解锁失败', true);
                            }
                            return Responses::response200(array(), 1, '解锁成功');
                        }
                    }
                    break;
                default:
            }
            return Responses::response200(array(), 1, '成功');
        }
    }

    /**
     * 加解锁——涉诉情况
     *  type 1加锁，2解锁
     * @return array
     */
    public function actionLawsuitLock()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $project_id = (int)Yii::$app->request->post('project_id');
            $stakeholder_id = (int)Yii::$app->request->post('stakeholder_id');
            $type = (int)Yii::$app->request->post('type');

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $models = ProjectInvestigationLawsuit::find()->where(array('project_id' => $project_id, 'stakeholder_id' => $stakeholder_id))->all();
            if (!empty($models)) {
                switch ($type) {
                    case 1:
                        //判断别人是否锁定
                        $isLockedData = $this->more_is_locked($models, $userId);
                        if (!$isLockedData['state']) {
                            return Responses::response400($isLockedData['msg'], true);
                        }

                        $LockingData = $this->more_locking($models, $userId);
                        if (!$LockingData['state']) {
                            return Responses::response400('加锁失败', true);
                        }
                        return Responses::response200(array(), 1, '加锁成功');
                        break;
                    case 2:
                        $unLockingData = $this->more_unlocking($models, $userId);
                        if (!$unLockingData['state']) {
                            return Responses::response400('解锁失败', true);
                        }
                        return Responses::response200(array(), 1, '解锁成功');
                        break;
                    default:
                }
            }
            return Responses::response200(array(), 1, '成功');
        }
    }


    /**
     * Displays a single ProjectInvestigation model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProjectInvestigation model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ProjectInvestigation();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ProjectInvestigation model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ProjectInvestigation model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ProjectInvestigation model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return ProjectInvestigation the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProjectInvestigation::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
